package com.gzx.plugin.fin.tech.service.impl;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.gzx.plugin.fin.tech.entity.GzxFinTechRecord;
import com.gzx.plugin.fin.tech.mapper.GzxFinTechRecordMapper;
import com.gzx.plugin.fin.tech.service.GzxFinTechRecordService;

import lombok.RequiredArgsConstructor;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.CommonSleepUtil;

/**
 * @author zjt
 * {@code @description}
 * {@code @date} 2025/4/3 17:46
 */
@Service
@RequiredArgsConstructor
public class GzxFinTechRecordServiceImpl implements GzxFinTechRecordService {

    private final GzxFinTechRecordMapper finTechRecordMapper;

    /**
     * 批量保存查询记录
     */
    @Override
    public void saveBatchRecord(List<ConsumerRecord<String, String>> recordList) {
        List<GzxFinTechRecord> finTechRecordList = getFinTechRecordList(recordList);
        List<List<GzxFinTechRecord>> batchList = Lists.partition(finTechRecordList, IntConstant.VALUE_1000);
        for (List<GzxFinTechRecord> batch : batchList) {
            String batchSql = batch.stream()
                    .map(s -> String.format("('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
                            escapeSql(s.getApiKey()),
                            escapeSql(s.getApiSecret()),
                            escapeSql(String.valueOf(s.getTimestamp())),
                            escapeSql(s.getNonce()),
                            escapeSql(s.getSignature()),
                            escapeSql(s.getClientIp()),
                            escapeSql(s.getRequestId()),
                            escapeSql(String.valueOf(s.getTotalCount())),
                            escapeSql(s.getCreateTime())))
                    .collect(Collectors.joining(", "));
            finTechRecordMapper.insertRecord(batchSql.replace("'null'", "null"));
            CommonSleepUtil.sleep(IntConstant.VALUE_100);
        }
    }

    @Override
    public void saveSingleRecord(GzxFinTechRecord finTechRecord) {
        finTechRecordMapper.insert(finTechRecord);
    }

    private List<GzxFinTechRecord> getFinTechRecordList(List<ConsumerRecord<String, String>> recordList) {
        return recordList.stream().map(consumerRecord -> JSON.parseObject(consumerRecord.value(), GzxFinTechRecord.class)).toList();
    }
}
